package com.atguigu.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.realtime.app.BaseAppV1;
import com.atguigu.realtime.bean.TradeOrderBean;
import com.atguigu.realtime.common.Constant;
import com.atguigu.realtime.util.AtguiguUtil;
import com.atguigu.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.AllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * @Author lzc
 * @Date 2022/5/30 10:03
 */
public class Dws_08_DwsTradeOrderWindow extends BaseAppV1 {
    public static void main(String[] args) {
        new Dws_08_DwsTradeOrderWindow().init(3008, 2, "Dws_08_DwsTradeOrderWindow", Constant.TOPIC_DWD_TRADE_ORDER_DETAIL);
    }
    
    @Override
    protected void handle(StreamExecutionEnvironment env,
                          DataStreamSource<String> stream) {
        // 1. 去重: 按照订单详情id去重, 保留最后一条
        SingleOutputStreamOperator<JSONObject> distinctedStream = distinctByOrderDetailId(stream);
        // 2. 统计当日独立下单用户和新下单用户
        SingleOutputStreamOperator<TradeOrderBean> beanStream = parseToBean(distinctedStream);
        // 3. 开窗聚合
        SingleOutputStreamOperator<TradeOrderBean> resultStream = windowAndAggregate(beanStream);
    
        // 4. 写出到clickhouse中
        writeToClickHouse(resultStream);
    }
    
    private void writeToClickHouse(SingleOutputStreamOperator<TradeOrderBean> resultStream) {
        resultStream.addSink(FlinkSinkUtil.getClickHouseSink(
            Constant.CLICKHOUSE_DB,
            "dws_trade_order_window",
            // insert into aa(a,b,c) values(?,?,?)
            TradeOrderBean.class
        ));
    }
    
    private SingleOutputStreamOperator<TradeOrderBean> windowAndAggregate(SingleOutputStreamOperator<TradeOrderBean> stream) {
       return stream
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<TradeOrderBean>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((bean, ts) -> bean.getTs())
            )
            .windowAll(TumblingEventTimeWindows.of(Time.seconds(5)))
            .reduce(
                new ReduceFunction<TradeOrderBean>() {
                    @Override
                    public TradeOrderBean reduce(TradeOrderBean b1,
                                                 TradeOrderBean b2) throws Exception {
                        b1.setOrderUniqueUserCount(b1.getOrderUniqueUserCount() + b2.getOrderUniqueUserCount());
                        b1.setOrderNewUserCount(b1.getOrderNewUserCount() + b2.getOrderNewUserCount());
                        b1.setOrderActivityReduceAmount(b1.getOrderActivityReduceAmount() + b2.getOrderActivityReduceAmount());
                        b1.setOrderCouponReduceAmount(b1.getOrderCouponReduceAmount() + b2.getOrderCouponReduceAmount());
                        b1.setOrderOriginTotalAmount(b1.getOrderOriginTotalAmount() + b2.getOrderOriginTotalAmount());
                        
                        return b1;
                    }
                },
                new AllWindowFunction<TradeOrderBean, TradeOrderBean, TimeWindow>() {
                    @Override
                    public void apply(TimeWindow window,
                                      Iterable<TradeOrderBean> values,
                                      Collector<TradeOrderBean> out) throws Exception {
                        String stt = AtguiguUtil.toDateTime(window.getStart());
                        String edt = AtguiguUtil.toDateTime(window.getEnd());
                        
                        long ts = System.currentTimeMillis();
    
                        TradeOrderBean bean = values.iterator().next();
                        bean.setStt(stt);
                        bean.setEdt(edt);
                        bean.setTs(ts);
                        out.collect(bean);
                    }
                }
            );
    }
    
    private SingleOutputStreamOperator<TradeOrderBean> parseToBean(SingleOutputStreamOperator<JSONObject> stream) {
        
        return stream
            .keyBy(obj -> obj.getString("user_id"))
            .process(new KeyedProcessFunction<String, JSONObject, TradeOrderBean>() {
                
                private ValueState<String> lastOrderDateState;
                
                @Override
                public void open(Configuration parameters) throws Exception {
                    lastOrderDateState = getRuntimeContext()
                        .getState(new ValueStateDescriptor<String>("lastOrderDateState", String.class));
                }
                
                @Override
                public void processElement(JSONObject obj,
                                           Context ctx,
                                           Collector<TradeOrderBean> out) throws Exception {
                    long ts = obj.getLong("ts") * 1000;
                    
                    String today = AtguiguUtil.toDate(ts);
                    String lastOrderDate = lastOrderDateState.value();
                    
                    TradeOrderBean.TradeOrderBeanBuilder builder = TradeOrderBean.builder();
                    
                    if (lastOrderDate == null) {
                        // 今天第一次下单, 而且是这个用户的第一次下单
                        builder.orderUniqueUserCount(1L);
                        builder.orderNewUserCount(1L);
                        
                        lastOrderDateState.update(today);
                    } else {
                        // 不是新用户 , 今天是否第一次?
                        if (!today.equals(lastOrderDate)) {
                            // 今天第一次
                            builder.orderUniqueUserCount(1L);
                            lastOrderDateState.update(today);
                        }
                        
                    }
                    // 如果是null, 则会自动转为0
                    builder
                        .orderActivityReduceAmount(obj.getDoubleValue("split_activity_amount"))
                        .orderCouponReduceAmount(obj.getDoubleValue("split_coupon_amount"))
                        .orderOriginTotalAmount(obj.getDoubleValue("split_original_amount"))
                        .ts(ts);
                    
                    out.collect(builder.build());
                }
            });
        
    }
    
    private SingleOutputStreamOperator<JSONObject> distinctByOrderDetailId(DataStreamSource<String> stream) {
        return stream
            .map(JSON::parseObject)
            .keyBy(obj -> obj.getString("id"))
            .process(new KeyedProcessFunction<String, JSONObject, JSONObject>() {
                
                private ValueState<JSONObject> lastOrderDetailState;
                
                @Override
                public void open(Configuration parameters) throws Exception {
                    // 状态中存储数据, 每新来一条数据,就比较时间, 新来的大于状态中的,更新状态中的数据
                    lastOrderDetailState = getRuntimeContext().getState(new ValueStateDescriptor<JSONObject>("lastOrderDetailState", JSONObject.class));
                }
                
                @Override
                public void processElement(JSONObject obj,
                                           Context ctx,
                                           Collector<JSONObject> out) throws Exception {
                    JSONObject lastOrderDetail = lastOrderDetailState.value();
                    if (lastOrderDetail == null) {
                        lastOrderDetailState.update(obj);
                        // 注册定时器: 处理时间5s后触发的定时器
                        ctx.timerService().registerProcessingTimeTimer(ctx.timerService().currentProcessingTime() + 5000);
                    } else {
                        
                        String lastTime = lastOrderDetail.getString("row_op_ts");
                        String currentTime = obj.getString("row_op_ts");
                        
                        // 如果currentTime > lastTime 更新状态. 否则什么都不做
                        // 2022-05-23 06:12:06.768Z  2022-05-23 06:12:06.8Z
                        // 判断是否大于等于 currentTime , 如果是 返回 true, 否则返回false
                        boolean isGreaterOrEqual = AtguiguUtil.compareLTZ(currentTime, lastTime);
                        if (isGreaterOrEqual) {
                            lastOrderDetailState.update(obj);
                        }
                    }
                }
                
                @Override
                public void onTimer(long timestamp,
                                    OnTimerContext ctx,
                                    Collector<JSONObject> out) throws Exception {
                    out.collect(lastOrderDetailState.value());
                }
            });
        
        
    }
}
